package com.GPT.filter;

import com.GPT.common.Jwt;
import com.GPT.domain.Newuser;
import com.GPT.service.UserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

public class JwtFilter implements Filter {

    @Autowired
    private UserService userService;
    private final UserDetailsService userDetailsService;

    // 构造方法
    public JwtFilter(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法，通常不需要在此处实现
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String token = httpRequest.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer " 前缀

            try {
                if (Jwt.validateToken(token)) {
                    Claims claims = Jwt.getClaims(token);
                    Long userId = Jwt.getUserId(token); // 获取用户ID

                    // 从数据库获取用户信息
                    Newuser user = userService.getById(userId);

                    if (user != null) {
                        // 创建一个包含用户权限的 Authentication 对象
                        Authentication auth = new UsernamePasswordAuthenticationToken(
                                user, null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));

                        // 将 Authentication 设置到 SecurityContext 中
                        SecurityContextHolder.getContext().setAuthentication(auth);
                    } else {
                        // 如果用户未找到，返回 401 错误
                        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User not found");
                        return;
                    }
                }
            } catch (ExpiredJwtException e) {
                // 处理过期的 JWT
                httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JWT token expired");
                return;
            }
        }

        // 继续处理请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 清理资源方法，通常不需要在此处实现
    }
}
